import { login, getSideMenu } from "@/api/user";
import { sessionSet, sessionGet, sessionRemove } from "@/utils/auth";

import Router, { resetRouter } from "@/router";
import Layout from "@/layout";
import store from "../index";
const getDefaultState = () => {
    return {
        // token: getToken(),
        name: sessionGet("userName") || "",
        avatar: "",
        routesMenu: []
    };
};

const state = getDefaultState();

const mutations = {
    RESET_STATE: state => {
        Object.assign(state, getDefaultState());
    },
    // SET_TOKEN: (state, token) => {
    //     state.token = token;
    // },
    SET_NAME: (state, name) => {
        sessionSet("userName", name);
        state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
    },
    SET_ROUTE: (state, routesMenu) => {
        state.routesMenu = routesMenu;
        Router.selfaddRoutes(routesMenu);
    }
};

const actions = {
    // 用户登录
    login({ commit, dispatch }, userInfo) {
        return new Promise((resolve, reject) => {
            const { userName, password, isFlag } = userInfo;
            store.commit("app/TOGGLE_LOADINGSHOW", false);
            if (isFlag) {
                //不用掉接口
                commit("SET_NAME", userName);
            } else {
                login({ userName, password })
                    .then(response => {
                        const { data } = response.data;
                        commit("SET_NAME", data.name);
                        dispatch("GenerateRoutes");
                        resolve(response);
                    })
                    .catch(error => {
                        reject(error);
                    });
            }
        });
    },

    /**
     * @param {动态添加路由}
     * @param {获取侧边栏路由}
     */
    GenerateRoutes({ commit, state }) {
        return new Promise((resolve, reject) => {
            const route = [...Router.options.routes];
            commit("SET_ROUTE", route);
            // getSideMenu().then(res => {
            //     let data = res.data.data;
            //     let filterData = formatTreeData(data);
            //     let routeData = filterAsyncRoutes(filterData);
            //     const route = [...Router.options.routes]
            //     const route = [...Router.options.routes, ...routeData];
            //     commit("SET_ROUTE", route);
            // });
        });
    },

    // 退出登录
    logout({ commit }) {
        return new Promise((resolve, reject) => {
            commit("SET_NAME", "");
            commit("SET_TOKEN", "");
            store.commit("app/ADD_VISITED_VIEW", []);
            // commit('app/ADD_VISITED_VIEW', [])
            resetRouter();
            // commit('RESET_STATE')
            sessionRemove("tabViews");
            sessionRemove("name");
            sessionStorage.clear();
            resolve();
        });
    },

    // 删除 token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken(); // must remove  token  first
            commit("RESET_STATE");
            resolve();
        });
    }
};

/**
 *
 * @param {根据parentId格式化成树结构} routes
 */
function formatTreeData(list, parentId = 0) {
    let parentObj = {};
    list.forEach(o => {
        parentObj[o.id] = o;
    });
    if (!parentId) {
        return list
            .filter(o => !parentObj[o.parentId])
            .map(o => ((o.children = formatTreeData(list, o.id)), o));
    } else {
        return list
            .filter(o => o.parentId == parentId)
            .map(o => ((o.children = formatTreeData(list, o.id)), o));
    }
}

/**
 *
 * @param 格式化routes
 * @param routes
 */
export function filterAsyncRoutes(data) {
    const arr = [];
    data.map(item => {
        const child = item.children.map(v => {
            let path = v.routerPath.substring(1, v.routerPath.length);
            return {
                path: path,
                name: v.moduleName,
                component: resolve =>
                    require(["@/views/" + v.modulePath + "/index.vue"], resolve),
                meta: { title: v.chineseName, icon: "example" }
            };
        });
        const param = {
            path: item.routerPath,
            name: item.moduleName,
            redirect: `${item.routerPath}/${child[0].path}`,
            component: Layout,
            meta: { title: item.chineseName, icon: "example" },
            children: child
        };
        if (child.length == 1) {
            param.alwaysShow = true;
        }
        arr.push(param);
    });

    return arr;
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
};